<?php

namespace App\Controller\AdminApi\Shop;

use App\Base\IRI;
use App\Base\BaseForm;
use App\Base\ActionBox\ActionBox;
use App\Base\SearchBox\SearchBox;
use App\Base\BaseController4Admin;
use App\Entity\MyData\MyDataValue;
use App\Entity\Sale\PromotionCategory;
use App\Entity\Sale\PromotionProduct;
use App\Repository\MyData\MyDataTemplateRepository;
use App\Repository\MyData\MyDataValueRepository;
use App\Repository\Sale\PromotionProductRepository;
use App\Repository\Shop\ShopCategoryRepository;
use App\Repository\Shop\ShopProductStorageRepository;
use Symfony\Component\Routing\Annotation\Route;

use App\Repository\Shop\ShopProductRepository as Repository;
use App\Entity\Shop\ShopProduct as Entity;

/**
 * @Route("/admin/")
 */
class ShopProductAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "ShopProduct";
    public $limit = 10;
    public $listRow = ["category.name","title","cover","views","sell","id"];

    /**
     * @Route("ShopProduct/form",name="ShopProductForm")
     */
    public function form(Repository $repository,
                         MyDataTemplateRepository $templateRepository,
                         MyDataValueRepository $myDataValueRepository,
                         ShopCategoryRepository $shopCategoryRepository
    )
    {
        $uid = $this->needToBeAdmin();$SaleJuan=0;
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        $next = 0;
        $prev = 0;
        if (!$entity) {
            $entity = new Entity();
        }else{
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["gt"=>["id"=>$data["id"]??0]]);
            $qb->setFirstResult(0)->setMaxResults(1);
            $qb->orderBy("A.id","ASC");
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $next = $rst[0]->getId();
                }
            }
            $qb = $repository->createQueryBuilder("A");
            createWhere($qb,["lt"=>["id"=>$data["id"]??0]]);
            $qb->orderBy("A.id","DESC");
            $qb->setFirstResult(0)->setMaxResults(1);
            $rst = $qb->getQuery()->execute();
            if (count($rst)==1) {
                if (isset($rst[0])) {
                    $prev = $rst[0]->getId();
                }
            }
        }
        $BaseForm = new BaseForm(Entity::class);
        //表单选项
        $BaseForm->addSelect("category","分类目录",$shopCategoryRepository->getSons4Setting())->ruleNotNull()->getData();
        $BaseForm->addItem("title")->ruleNotNull()->getData();
        $BaseForm->addItem("subTitle")->getData();
        $BaseForm->addItem("cover")->ruleNotNull()->getData();
        $BaseForm->addItem("video")->getData();
        $BaseForm->addItem("intro")->getData();
        $BaseForm->addItem("pics")->getData();
        $BaseForm->addItem("views")->ruleNotNull()->getData();
        $BaseForm->addItem("sell")->ruleNotNull()->getData();
        //预支参数
        $template = $entity->getParamTemplate();
        $promotionProducts = $entity->getPromotions();
        $BaseForm->addLine('规格参数');
        //测试其他参数的录入
        $templates = $templateRepository->get4Choice();
        $BaseForm->addSelect("paramTemplate","参数模板",$templates)->setWidth(12)->getData();
        $entity = $this->toArray($entity);
        if ($template) {
            $templateValues = $myDataValueRepository->getForm4Entity($BaseForm,$template,Entity::class,$entity["id"]);
            //补充额外参数值
            $entity = array_merge($entity,$templateValues);
        }

        $BaseForm->addLine('活动设置');
        $BaseForm->addList("huodong","活动会场",[])->setName("PromotionCategory")->getData();
        $promotions = [];
        if ($promotionProducts) {
            foreach ($promotionProducts as $row) {
                $promotions[] = IRI::createIRIStringFromEntity(PromotionCategory::class,$row->getCategory()->getId());
            }
        }
        $entity["huodong"]=$promotions;

        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "信息编辑",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
            "next"   => $next,
            "prev"   => $prev,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("ShopProduct/submit",name="ShopProductSubmit",methods={"POST"})
     */
    public function submit(
        Repository $repository,
        MyDataValueRepository $myDataValueRepository,
        ShopProductStorageRepository $storageRepository,
        PromotionProductRepository $promotionProductRepository
    )
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
        if (!$entity) {$entity = new  Entity();}
        /**@var $ShopProduct Entity*/
        $ShopProduct = $this->updateEntity($data,Entity::class,$entity);
        $this->myEm()->persist($ShopProduct);$this->myEm()->flush();
        $template = $entity->getParamTemplate();
        $myDataValueRepository->saveValues($template,$data,Entity::class,$entity->getId());

        //更新产品库存
        $storageRepository->updateProductStorageRows($ShopProduct);

        //处理活动标签
        $huodongArray = $data["huodong"]??[];
        $oldData = $ShopProduct->getPromotions();
        foreach ($oldData as $oldOne) {
            if (!in_array(IRI::createIRIStringFromEntity(PromotionProduct::class,$oldOne->getId()),$huodongArray)) {
                $ShopProduct->removePromotion($oldOne);
            }
        }
        $this->myEm()->persist($ShopProduct);$this->myEm()->flush();

        foreach ($huodongArray as $iriString) {
            $tmp = myExplodeNumbers( $iriString );
            $id = end($tmp);
            $promotionProductRepository->findOrCreate($id,$entity);
        }




        return $this->json_out(1,"保存成功","/admin/list/Product?en=ShopProduct");
    }

    /**
     * @Route("ShopProduct/list",name="ShopProductGetList")
     */
    public function getList(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $per_page   = $this->limit;
        $page       = $data["page"]??1;
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];

        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $this->setGroups("prod","cat");
        $list= $this->normalize($list);

        //列表计数
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        //表头数据和列表内展示形式
        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        //额外数据示例
        //$config["KEY"] = (new Common())->setName("NAME")->setWidth("300");

        //设置筛选数据表单
        $sb = new SearchBox();
        $sb->setExcel(false);
        //todo 设置筛选数据
        //设置筛选数据表单
        $ab = new ActionBox();
        //todo 设置筛选数据
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => $this->listRow,
            "config"    => $config,
            'lists'     => $list,
            'searchBox' => $sb->createData(),
            'actionBox' => $ab->createData(),
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }

    /**
     * @Route("ShopProduct/excel",name="ShopProductGetListExcel")
     */
    public function getListExcel(Repository $repository)
    {
        $this->needToBeAdmin();
        $data       = $this->getRequestData();
        $where      = $data['_where']??[];
        $search     = $data['_search']??[];
        $order      = $data["_order"]??[];
        //列表筛选
        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $list = $qb->getQuery()->execute();
        $list= $this->normalize($list);

        $config = getEntityAnnotationData(Entity::class);
        if (count($list)>0) {
            $row = $list[0];
            $title = [];
            foreach ($row as $key=>$value) {
                $title[] = isset($config[$key])?$config[$key]->cnName:"";
            }
        }else{
            $title=[
                "","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
            ];
        }
        $this->excelOut($title,$list,"123.xls");
    }


    /**
     * @Route("ShopProduct/delete",name="ShopProductDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * @Route("ShopProduct/action",name="ShopProductAction",methods={"GET","POST"})
     */
    public function UserAction(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        $action = $this->getRequestData()["_action"]??[];
        //移除没有值的项
        foreach ($action as $key=>$value) {
            if ($value === "") {
                unset($action[$key]);
            }
        }
        foreach ($ids as $id) {
            if ($entity= $repository->find($id)) {
                $entity = $this->updateEntity($action,Entity::class,$entity);
                $this->myEm()->persist($entity);
            }
        }
        $this->myEm()->flush();
        return $this->json_out(1,'修改成功');
    }

    /**
     * @Route("ShopProduct/copy",name="ShopProductCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("ShopProduct/search",name="ShopProductGetList4EntitySelect")
     */
    public function getList4EntitySelect(Repository $repository)
    {
        $this->needToBeAdmin();
        $data = $this->getRequestData();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $where = $data['_where']??[];
        $search = $data['_search']??[];
        $order = $data["_order"]??[];

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        createOrderBy($qb,$order);
        $qb->setFirstResult($page*$this->limit - $this->limit)->setMaxResults($this->limit);
        $list = $qb->getQuery()->execute();
        $this->setGroups('prod',"cat");
        $list= $this->normalize($list);

        $qb = $repository->createQueryBuilder("A");
        createWhere($qb,$where);
        createSearch($qb,$search,[],"or");
        $qb->select("count(A.id) as num");
        $total = $qb->getQuery()->execute()[0]["num"]??0;

        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "{$this->entityName}",
            'title'     => "列表",
            'header'     => ["category.name","title"],
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("ShopProduct/viewer",name="ShopProductList4EntityViewer")
     */
    public function ShopProductList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("ShopProduct/choice",name="ShopProductList4ListChoice")
     */
    public function ShopProductList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }
}
